package org.dromara.exam.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.io.FileUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.MimeTypeUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.exam.domain.bo.ExamRepoBo;
import org.dromara.exam.domain.bo.ExamTemplateImportBo;
import org.dromara.exam.domain.dto.ProjectSetting;
import org.dromara.exam.domain.vo.ExamRepoVo;
import org.dromara.exam.domain.dto.TemplateSchema;
import org.dromara.exam.domain.vo.RepoInfoVo;
import org.dromara.exam.service.IExamRepoService;
import org.dromara.exam.service.IExamTemplateService;
import org.dromara.system.domain.vo.ImageVo;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * 题库
 *
 * @author xiyin321
 * @date 2024-04-11
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/exam/repo/")
public class ExamRepoController extends BaseController {

    private final IExamRepoService repoService;
    private final IExamTemplateService templateService;
    private final ISysOssService ossService;

    /**
     * 分页查询题库
     */
    @SaCheckPermission(value = {"exam:questionSet:list", "exam:questionSet:query"}, mode = SaMode.OR)
    @GetMapping("page")
    public TableDataInfo<ExamRepoVo> list(ExamRepoBo bo, PageQuery pageQuery) {
        return repoService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询题库列表
     * @param bo
     * @return
     */
    @SaCheckPermission("exam:questionSet:option")
    @GetMapping("list")
    public R<List<ExamRepoVo>> all(ExamRepoBo bo) {
        return R.ok(repoService.queryList(bo));
    }

    /**
     * 查询题库列表及题库下的题目
     */
    @SaCheckPermission("exam:questionSet:option")
    @GetMapping("listAndTemplate")
    public R<List<RepoInfoVo>> listAndQuestion(ExamRepoBo bo) {
        return R.ok(repoService.queryListAndTemplate(bo));
    }

    /**
     * 导入数据
     */
    @SaCheckPermission("exam:questionSet:import")
    @PostMapping(value = "importData")
    @Log(title = "题库", businessType = BusinessType.IMPORT)
    public R<Void> importData(@RequestPart("file") MultipartFile file, ExamTemplateImportBo bo) {
        bo.setFile(file);
        templateService.importTemplate(bo);
        return R.ok("导入成功");
    }

    /**
     * 下载模板
     * @param name
     * @return
     */
    @GetMapping("downloadTemplate")
    public ResponseEntity<Resource> downloadTemplate(String name) {
        return repoService.downloadTemplate(name);
    }

    /**
     * 导出题库列表
     */
    @SaCheckPermission("exam:questionSet:export")
    @Log(title = "题库", businessType = BusinessType.EXPORT)
    @PostMapping("export")
    public void export(ExamRepoBo bo, HttpServletResponse response) {
        List<ExamRepoVo> list = repoService.queryList(bo);
        ExcelUtil.exportExcel(list, "题库", ExamRepoVo.class, response);
    }

    /**
     * 获取题库详细信息
     *
     * @param repoId 主键
     */
    @SaCheckPermission("exam:questionSet:query")
    @GetMapping("{repoId}")
    public R<ExamRepoVo> getInfo(@NotNull(message = "主键不能为空")
                                        @PathVariable Long repoId) {
        return R.ok(repoService.queryById(repoId));
    }

    /**
     * 新增题库
     */
    @SaCheckPermission("exam:questionSet:add")
    @Log(title = "题库", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ExamRepoBo bo) {
        return toAjax(repoService.insertByBo(bo));
    }

    /**
     * 修改题库
     */
    @SaCheckPermission("exam:questionSet:edit")
    @Log(title = "题库", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ExamRepoBo bo) {
        return toAjax(repoService.updateByBo(bo));
    }


    /**
     * 删除题库
     *
     * @param repoIds 主键串
     */
    @SaCheckPermission("exam:questionSet:remove")
    @Log(title = "题库", businessType = BusinessType.DELETE)
    @DeleteMapping("{repoIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable List<Long> repoIds) {
        if (templateService.checkRepoExistTemplate(repoIds)) {
            return R.warn("题库存在数据,不允许删除");
        }
        return toAjax(repoService.deleteWithValidByIds(repoIds, true));
    }

    /**
     * 从题库挑选题目
     * @param bo
     * @return
     */
    @PostMapping("pick")
    public R<List<TemplateSchema>> pickQuestionFromBank(@RequestBody List<ProjectSetting.RandomQuestionCondition> bo) {
        return R.ok(repoService.pickTemplateFromRepo(bo));
    }
}
